package com.btioe.yugong.common.conf;

import com.iote.rock.common.entity.BizResult;
import com.iote.rock.common.exception.BizException;
import lombok.Data;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.Objects;
import java.util.Properties;


@Data
public class ProfileBO {
    @FieldAlias("canal.server.url")
    private String canalUrl;
    @FieldAlias("canal.server.port")
    private Integer canalPort;
    @FieldAlias("consumer.db.url")
    private String cDbUrl;
    @FieldAlias("consumer.db.name")
    private String cDbName;
    @FieldAlias("consumer.db.account.name")
    private String cDbUser;
    @FieldAlias("consumer.db.account.password")
    private String cDbPwd;


    public static ProfileBO buildFromProperties(Properties properties) throws IllegalAccessException {
        ProfileBO profileBO = new ProfileBO();
        for (Field field : ProfileBO.class.getDeclaredFields()) {
            FieldAlias annotation = field.getAnnotation(FieldAlias.class);
            if (Objects.isNull(annotation)) {
                continue;
            }
            String property = properties.getProperty(annotation.value());
            if (StringUtils.isEmpty(property)) {
                throw BizException.create(BizResult.error("", annotation.value() + " is null"));
            }
            if (Integer.class == field.getType()) {
                field.set(profileBO, Integer.valueOf(property));
            } else {
                field.set(profileBO, property);
            }
        }
        return profileBO;
    }
}
